package com.hdl.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.hdl.entity.HdlUser;
import com.hdl.entity.MallProduct;

/**
 * 保存头像工具类
 * @author Administrator
 *
 */
public class UploadLogUtil {

	
	//创建一个下载的方法，需要时调用
	 public static void upload(HttpServletRequest request, HttpServletResponse response,HdlUser user) {
			 	//1.创建一个磁盘工厂对象
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			//2.通过工厂对象创建上传对象
			ServletFileUpload fUpload = new ServletFileUpload(factory);
			
			//3.通过上传对象解析前端发送的复合型表单数据
			List<FileItem> list = null;
			HashMap<String, String> map = new HashMap<>();
			try {
				//设置字符编码
				request.setCharacterEncoding("utf-8");
			    //通过上传对象解析请求中的数据,获得集合
			    list = fUpload.parseRequest(request);
			    for (FileItem fItem:list) {
			        //判断是否非文本信息
			        if(!fItem.isFormField()){
			            //2.修改上传图片的名字
			            //使用UUID--生成唯一的ID值---wehfiw123%@#$!6fwef_f.jpg
			            UUID uuid = UUID.randomUUID();
			            String path = request.getServletContext().getRealPath("Upload");
			            File file = new File(path);
			            if(!file.exists()){
			                file.mkdirs();
			            }
			            //拼接路径和图片名字(uuid生成的随机字符串拼接上图片名字)
			            File file1 = new File(file, uuid.toString() + "_" + fItem.getName());
			            IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
			            //存储的路径不能为绝对路径
			            user.setHdlUserLog("Upload/"+uuid.toString() + "_" + fItem.getName());
			        }else{
			            //通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)
			            String value = map.get(fItem.getFieldName());
			            //第一次存储
			            if(value == null){
			                map.put(fItem.getFieldName(),new String(fItem.getString().getBytes("ISO-8859-1"),"utf-8"));
			            }else{//多次存储(多选框)
			                map.put(fItem.getFieldName(),value+","+fItem.getString());
			            }
			        }
			    }
			    //防止时间类型转换出错
				DateConverter dc = new DateConverter();//创建时间类型转换器
				dc.setPattern("yyyy-MM-dd");//设置转换格式
				ConvertUtils.register(dc, java.util.Date.class);
			    
			    //利用该方法把map集合的数据存放到student对象中
			    BeanUtils.populate(user,map);
			    
			} catch (FileUploadException e) {
			    e.printStackTrace();
			} catch (FileNotFoundException e) {
			    e.printStackTrace();
			} catch (IOException e) {
			    e.printStackTrace();
			} catch (IllegalAccessException e) {
			    e.printStackTrace();
			} catch (InvocationTargetException e) {
			    e.printStackTrace();
			} 

	 }
	 
	 /**
	  * uploadProduct 商品文件上传
	  * @param request
	  * @param response
	  * @param product
	  */
	 public static void uploadProduct(HttpServletRequest request, HttpServletResponse response,MallProduct product) {
		 	//1.创建一个磁盘工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		
		//2.通过工厂对象创建上传对象
		ServletFileUpload fUpload = new ServletFileUpload(factory);
		
		//3.通过上传对象解析前端发送的复合型表单数据
		List<FileItem> list = null;
		HashMap<String, String> map = new HashMap<>();
		try {
			//设置字符编码
			request.setCharacterEncoding("utf-8");
		    //通过上传对象解析请求中的数据,获得集合
		    list = fUpload.parseRequest(request);
		    for (FileItem fItem:list) {
		        //判断是否非文本信息
		        if(!fItem.isFormField()){
		            //2.修改上传图片的名字
		            //使用UUID--生成唯一的ID值---wehfiw123%@#$!6fwef_f.jpg
		            UUID uuid = UUID.randomUUID();
		            String path = request.getServletContext().getRealPath("Upload");
		            File file = new File(path);
		            if(!file.exists()){
		                file.mkdirs();
		            }
		            //拼接路径和图片名字(uuid生成的随机字符串拼接上图片名字)
		            File file1 = new File(file, uuid.toString().replace("-", "") + "_" + fItem.getName());
		            IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
		            //存储的路径不能为绝对路径
		            product.setMallProductPath("Upload/"+uuid.toString().replace("-", "") + "_" + fItem.getName());
		        }else{
		            //通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)
		            String value = map.get(fItem.getFieldName());
		            //第一次存储
		            if(value == null){
		                map.put(fItem.getFieldName(),new String(fItem.getString().getBytes("ISO-8859-1"),"utf-8"));
		            }else{//多次存储(多选框)
		                map.put(fItem.getFieldName(),value+","+fItem.getString());
		            }
		        }
		    }
		    //防止时间类型转换出错
			DateConverter dc = new DateConverter();//创建时间类型转换器
			dc.setPattern("yyyy-MM-dd");//设置转换格式
			ConvertUtils.register(dc, java.util.Date.class);
		    
		    //利用该方法把map集合的数据存放到对象中
		    BeanUtils.populate(product,map);
		    
		} catch (FileUploadException e) {
		    e.printStackTrace();
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		} catch (IllegalAccessException e) {
		    e.printStackTrace();
		} catch (InvocationTargetException e) {
		    e.printStackTrace();
		} 

}
}
